package cn.adair.wechat;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;

import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import cn.adair.wechat.listener.OnLoginListener;
import cn.adair.wechat.listener.OnPayListener;
import cn.adair.wechat.listener.OnShareListener;

/**
 * 微信二次封装
 */
public class WeChat {

    public IWXAPI mWxApi;
    private static WeChat mWeChat;

    public WeChat(Context context, String Wx_APPid) {
        mWxApi = WXAPIFactory.createWXAPI(context, null);
        mWxApi.registerApp(Wx_APPid);
    }

    public static void init(Context context, String wx_appid) {
        if (mWeChat == null) {
            mWeChat = new WeChat(context, wx_appid);
        }
    }

    public static WeChat instance() {
        return mWeChat;
    }

    public IWXAPI iWxApi() {
        return mWxApi;
    }

    private OnPayListener mPayListener;

    /**
     * 发起微信支付
     */
    public void doPay(String json, OnPayListener listener) {
        mPayListener = listener;
        if (!mWxApi.isWXAppInstalled()) {
            mPayListener.onFailure("未安装微信", WeChatCode.ERROR_NOT_INSTALLED);
            return;//未安装微信
        }
        if (mWxApi.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            mPayListener.onFailure("微信版本过低", WeChatCode.ERROR_NOT_SUPPORTED);
            return;
        }

        JSONObject mParam;
        try {
            mParam = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
            mPayListener.onFailure("支付参数错误", WeChatCode.ERROR_PAY_PARAMS);
            return;
        }
        if (TextUtils.isEmpty(mParam.optString("appId"))
                || TextUtils.isEmpty(mParam.optString("partnerId"))
                || TextUtils.isEmpty(mParam.optString("prepayId"))
                || TextUtils.isEmpty(mParam.optString("packageValue"))
                || TextUtils.isEmpty(mParam.optString("nonceStr"))
                || TextUtils.isEmpty(mParam.optString("timeStamp"))
                || TextUtils.isEmpty(mParam.optString("sign"))) {
            mPayListener.onFailure("支付参数错误", WeChatCode.ERROR_PAY_PARAMS);
            return;
        }

        PayReq req = new PayReq();
        req.appId = mParam.optString("appId");
        req.partnerId = mParam.optString("partnerId");
        req.prepayId = mParam.optString("prepayId");
        req.packageValue = mParam.optString("packageValue");
        req.nonceStr = mParam.optString("nonceStr");
        req.timeStamp = mParam.optString("timeStamp");
        req.sign = mParam.optString("sign");

        mWxApi.sendReq(req);
    }

    /**
     * 微信支付回调
     */
    public void onPayResponse(int error_code) {
        switch (error_code) {
            case 0://成功
                mPayListener.onSuccess();
                break;
            case -1://错误
                mPayListener.onFailure("微信支付失败", WeChatCode.ERROR_PAY_FAILURE);
                break;
            case -2: //取消
                mPayListener.onCancel();
                break;
        }
    }

    private OnShareListener mShareListener;

    public void doShareImage(int scene, Bitmap bm, OnShareListener listener) {
        mShareListener = listener;
        if (null == bm) {
            mShareListener.onFailure("分享图片不存在", WeChatCode.ERROR_SHARE_PARAMS);
        }
        WXImageObject imgObj = new WXImageObject(bm);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bm, 150, 150, true);
        bm.recycle();
        msg.thumbData = WeChatUtil.bmpToByteArray(thumbBmp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = WeChatUtil.buildTransaction("img");
        req.message = msg;
        req.scene = scene;
        mWxApi.sendReq(req);
    }

    /**
     * 微信分享回调
     */
    public void onShareResponse(int error_code) {
        switch (error_code) {
            case 0: //分享完成
                mShareListener.onSuccess();
                break;
            case -2: // 分享取消
            case -4: // 分享被拒绝
                mShareListener.onFailure("微信分享失败", WeChatCode.ERROR_PAY_FAILURE);
                break;
        }
    }

    private OnLoginListener mLoginListener;

    public void doLogin(OnLoginListener listener) {
        mLoginListener = listener;
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        mWxApi.sendReq(req);
    }

    public void onLoginResponse(BaseResp baseResp) {
        if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
            String code = ((SendAuth.Resp) baseResp).code;
            mLoginListener.onSuccess(code);
        } else {
            mLoginListener.onFailure("登录失败", WeChatCode.ERROR_LOGIN_FAILURE);
        }
    }

    /**
     * 微信回调 转 自定义回调
     */
    public void onWeChatResponse(BaseResp response) {
        Log.e("CallbackActivity", "----------------------------------------------------23");
        switch (response.getType()) {
            case ConstantsAPI.COMMAND_SENDAUTH:             // 授权登录
                this.onLoginResponse(response);
                break;
            case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:    // 微信分享
                this.onShareResponse(response.errCode);
                break;
            case ConstantsAPI.COMMAND_PAY_BY_WX:            // 微信支付
                this.onPayResponse(response.errCode);
                break;
        }
    }

}
